import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';

/// 备份设置的全局状态管理
class BackupProvider with ChangeNotifier {
  static const String _keyAutoBackupPhotos = 'auto_backup_photos';
  static const String _keyAutoBackupVideos = 'auto_backup_videos';
  static const String _keyMaxBackupCount = 'max_backup_count';
  static const String _keyDeviceName = 'device_name';

  bool _autoBackupPhotos = true;
  bool _autoBackupVideos = true;
  int _maxBackupCount = 3;
  bool _isLoading = false;
  String _deviceName = '咕噜设备';

  /// 是否自动备份照片
  bool get autoBackupPhotos => _autoBackupPhotos;

  /// 是否自动备份视频
  bool get autoBackupVideos => _autoBackupVideos;

  /// 并行备份数量
  int get maxBackupCount => _maxBackupCount;

  /// 是否正在加载
  bool get isLoading => _isLoading;

  /// 设备名称
  String get deviceName => _deviceName;

  BackupProvider() {
    _loadSettings();
    _initDeviceName();
  }

  /// 初始化设备名称
  Future<void> _initDeviceName() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      // 尝试从SharedPreferences获取设备名称
      String? savedName = prefs.getString(_keyDeviceName);

      // 首先设置已保存名称（如果有）
      if (savedName != null && savedName.isNotEmpty) {
        _deviceName = savedName;
        notifyListeners();
      }

      // 如果有开关处于打开状态，刷新设备名
      if (_autoBackupPhotos || _autoBackupVideos) {
        // 尝试获取实际设备名称
        String? name = await _getDeviceName();
        if (name != null && name.isNotEmpty && name != _deviceName) {
          _deviceName = name;
          // 保存获取到的设备名称
          await prefs.setString(_keyDeviceName, name);
          notifyListeners();
        }
      } else if (savedName == null || savedName.isEmpty) {
        // 如果无法获取设备名称，生成一个唯一标识符
        _deviceName =
            '咕噜设备-${DateTime.now().millisecondsSinceEpoch.toString().substring(7)}';
        await prefs.setString(_keyDeviceName, _deviceName);
        notifyListeners();
      }
    } catch (e) {
      debugPrint('获取设备名称失败: $e');
      // 确保即使出现异常，也能设置一个默认值
      _deviceName = '咕噜设备';
      notifyListeners();
    }
  }

  /// 获取实际设备名称
  Future<String?> _getDeviceName() async {
    try {
      if (Platform.isAndroid) {
        // Android设备可以尝试获取设备型号
        return await _getAndroidDeviceName();
      } else if (Platform.isIOS) {
        // iOS设备可以尝试获取设备名
        return await _getIOSDeviceName();
      } else if (Platform.isWindows) {
        // Windows设备获取计算机名
        return await _getWindowsDeviceName();
      } else if (Platform.isMacOS) {
        // macOS设备获取主机名
        return await _getMacOSDeviceName();
      }
    } catch (e) {
      debugPrint('获取设备名称失败: $e');
    }
    return null;
  }

  /// 获取Android设备名称
  Future<String?> _getAndroidDeviceName() async {
    try {
      // 这里使用Android设备的型号作为设备名
      String manufacturer =
          await _getPlatformProperty('getprop ro.product.manufacturer') ?? '';
      String model =
          await _getPlatformProperty('getprop ro.product.model') ?? '';

      if (manufacturer.isNotEmpty && model.isNotEmpty) {
        return '$manufacturer $model';
      } else if (model.isNotEmpty) {
        return model;
      }
    } catch (e) {
      debugPrint('获取Android设备名称失败: $e');
    }
    return null;
  }

  /// 获取iOS设备名称
  Future<String?> _getIOSDeviceName() async {
    try {
      // 这里使用iOS设备的名称
      String? name = await _getPlatformProperty('hostname');
      return name;
    } catch (e) {
      debugPrint('获取iOS设备名称失败: $e');
    }
    return null;
  }

  /// 获取Windows设备名称
  Future<String?> _getWindowsDeviceName() async {
    try {
      final result = await Process.run('hostname', [], runInShell: true);
      if (result.exitCode == 0) {
        String output = result.stdout.toString().trim();
        if (output.isNotEmpty) {
          return 'PC-$output';
        }
      }
    } catch (e) {
      debugPrint('获取Windows设备名称失败: $e');
      // 使用备用方法获取
      try {
        final computerName = Platform.environment['COMPUTERNAME'];
        if (computerName != null && computerName.isNotEmpty) {
          return 'PC-$computerName';
        }
      } catch (e) {
        debugPrint('获取Windows环境变量失败: $e');
      }
    }
    return null;
  }

  /// 获取macOS设备名称
  Future<String?> _getMacOSDeviceName() async {
    try {
      final result = await Process.run('scutil', ['--get', 'ComputerName']);
      if (result.exitCode == 0) {
        String output = result.stdout.toString().trim();
        if (output.isNotEmpty) {
          return output;
        }
      }
    } catch (e) {
      debugPrint('获取macOS设备名称失败: $e');
      // 尝试使用hostname命令
      try {
        final hostnameResult = await Process.run('hostname', []);
        if (hostnameResult.exitCode == 0) {
          String output = hostnameResult.stdout.toString().trim();
          if (output.isNotEmpty) {
            return 'Mac-$output';
          }
        }
      } catch (e) {
        debugPrint('获取macOS主机名失败: $e');
      }
    }
    return null;
  }

  /// 获取平台特定属性
  Future<String?> _getPlatformProperty(String command) async {
    try {
      ProcessResult result = await Process.run('sh', ['-c', command]);
      if (result.exitCode == 0) {
        String output = result.stdout.toString().trim();
        if (output.isNotEmpty) {
          return output;
        }
      }
    } catch (e) {
      debugPrint('执行命令失败: $e');
    }
    return null;
  }

  /// 重新获取并刷新设备名称
  Future<void> refreshDeviceName() async {
    try {
      // 尝试获取实际设备名称
      String? name = await _getDeviceName();
      if (name != null && name.isNotEmpty) {
        _deviceName = name;

        // 保存获取到的设备名称
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(_keyDeviceName, name);
        notifyListeners();
        return;
      }

      // 如果获取失败，使用默认名称
      _deviceName = '咕噜设备';
      notifyListeners();
    } catch (e) {
      debugPrint('刷新设备名称失败: $e');
      // 确保即使出现异常，也不会影响UI
    }
  }

  /// 加载备份设置
  Future<void> _loadSettings() async {
    _setLoading(true);
    try {
      final prefs = await SharedPreferences.getInstance();
      _autoBackupPhotos = prefs.getBool(_keyAutoBackupPhotos) ?? true;
      _autoBackupVideos = prefs.getBool(_keyAutoBackupVideos) ?? true;
      _maxBackupCount = prefs.getInt(_keyMaxBackupCount) ?? 3;
      _deviceName = prefs.getString(_keyDeviceName) ?? '咕噜设备';
      notifyListeners();
    } catch (e) {
      debugPrint('加载备份设置失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 设置自动备份照片
  Future<void> setAutoBackupPhotos(bool value) async {
    if (_autoBackupPhotos == value) return;

    _autoBackupPhotos = value;
    notifyListeners();

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_keyAutoBackupPhotos, value);
    } catch (e) {
      debugPrint('保存自动备份照片设置失败: $e');
    }
  }

  /// 设置自动备份视频
  Future<void> setAutoBackupVideos(bool value) async {
    if (_autoBackupVideos == value) return;

    _autoBackupVideos = value;
    notifyListeners();

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_keyAutoBackupVideos, value);
    } catch (e) {
      debugPrint('保存自动备份视频设置失败: $e');
    }
  }

  /// 设置并行备份数量
  Future<void> setMaxBackupCount(int value) async {
    if (_maxBackupCount == value || value < 1 || value > 5) return;

    _maxBackupCount = value;
    notifyListeners();

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt(_keyMaxBackupCount, value);
    } catch (e) {
      debugPrint('保存并行备份数量设置失败: $e');
    }
  }

  /// 设置加载状态
  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  /// 重置为默认设置
  Future<void> resetToDefaults() async {
    _autoBackupPhotos = true;
    _autoBackupVideos = true;
    _maxBackupCount = 3;
    // 不重置设备名称
    notifyListeners();

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_keyAutoBackupPhotos, true);
      await prefs.setBool(_keyAutoBackupVideos, true);
      await prefs.setInt(_keyMaxBackupCount, 3);
    } catch (e) {
      debugPrint('重置备份设置失败: $e');
    }
  }
}
